#!/bin/bash

set -e

TUNA_URL=https://mirrors.tuna.tsinghua.edu.cn
PACKAGE_DIR=/opt/downloads
INSTALL_DIR=/opt/soft
PROJECTS=(
  [java]=AdoptOpenJDK
  [hadoop]=apache/hadoop/common
  [hive]=apache/hive/
)

# 获取可用版本号
getVersionInfo() {
  PROJECT_URL=${PROJECTS[$1]}
  VERSIONS_URL=${TUNA_URL}/${PROJECT_URL}
  printf "${VERSIONS_URL}\n"
  # CURRENT_VALID_VERSIONS=$(curl -s ${TUNA_URL}/${PROJECT}/ | grep -Eo "\"[0-9]{1,2}\"" | sed 's/"//g' | sort -n | sed ':a;N;s/\n/, /g;ba')
  # printf "当前可用$1版本为${CURRENT_VALID_VERSIONS}\n请输入你想安装的$1版本号(默认版本为8):"
  # read SELECTED_VERSION
}

# 获取下载地址
getDownloadAdress() {
  # JDK_FILE=$(curl -s ${TOTAL_URL} | grep -Eo "Open(\w|-|\.)+.gz" | sed -n '1p')
  # JDK_FILE_URL=${TOTAL_URL}${JDK_FILE}
  echo $JDK_FILE_URL
}

# 解压安装
install() {
  NAME=$1
  VERSION=$2
  PACKAGE=${PACKAGE_DIR}/${NAME}-${VERSION}.tar.gz
  HOME=${INSTALL_DIR}/${NAME}-${VERSION}
  UPPER_HOME_NAME=$(echo ${NAME} | tr 'a-z' 'A-Z')_HOME
  #curl ${JDK_FILE_URL} -o ${PACKAGE}
  #tar -zxf ${PACKAGE} -C ${INSTALL_DIR}/${NAME}-${VERSION}
  printf "export ${UPPER_HOME_NAME}=${HOME}\nexport PATH=\${PATH}:\${${UPPER_HOME_NAME}}/bin\n" #>${HOME}/.bashrc
}

# 创建目录
createDirectory() {
  [[ -d $1 ]] || mkdir -p $1
}

# 检查字符串包含
contains() {
  [[ 0 -lt $(echo $1 | grep -wc $2) ]] || (echo "$2不在$1中" && exit 1)
}

# 检测软件安装情况
softExists() {
  [[ $(command -v $1) ]] && return 0 || return 1
}

# 安装向导
wizard() {
  if [[ 'y' = $2 ]]; then
    getVersionInfo $1
  else
    read -p "是否安装 $1: [Y/N]?" answer
    case $answer in
    Y | y)
      wizard $1 $answer
      ;;
    *)
      wizard $1
      ;;
    esac
  fi
  wait
}

# 信息打印
menu() {
  printf "================= 大数据自动安装脚本 =================\n"
  printf "================= 版本：%-12s =================\n" 0.1
  printf "================= 状态：%-12s =================\n" ${?:=无}
  printf "目前支持安装\n1.Java\n2.Hadoop\n3.Hive\n4.顺序选择安装\n0.退出\n请输入对应的号码来安装："
  read num
  case "$num" in
  1)
    wizard java y
    menu
    ;;
  2)
    wizard hadoop y
    menu
    ;;
  3)
    wizard hive y
    menu
    ;;
  4)
    wizard java y
    wizard hadoop n
    wizard hive n
    menu
    ;;
  0)
    exit 0
    ;;
  esac

}

clear
menu
